package cn.com.kh;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message.RecipientType;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Properties;

public class SendMail {
    private static final Log log = LogFactory.getLog(SendMail.class);

    public static void goSendMail(String host, int port, String sendAdderss, String username, String password, String receviceAddress, String subject, String content, String type, String emlFilePath, List<?> attachmentList) throws Exception {
        // 输出要发送调用信息
        log.debug("SendMail输出要发送调用信息" + "-host:" + host + "-port:" + port + "-sendAdderss:" + sendAdderss + "-username:" + username + "-receviceAddress:" + receviceAddress + "-subject:" + subject + "-type:" + type + "-emlFilePath:" + emlFilePath);

        // 连接邮件服务器的参数配置
        Properties properties = new Properties();
        properties.put("mail.transport.protocol", "smtp");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);

        log.debug("连接邮件服务器的参数配置" + "-host:" + host + "-port:" + port);

        // 设置系统对附件名处理方式
        System.setProperty("mail.mime.splitlongparameters", "false");

        // 创建Session对象
        Session session = Session.getInstance(properties);

        // 设置调试信息在控制台打印出来
        session.setDebug(true);

        // 创建邮件的实例对象
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(sendAdderss));
        message.setRecipients(RecipientType.TO, new InternetAddress[]{new InternetAddress(receviceAddress)});
        message.setSubject(subject, "UTF-8");
        MimeMultipart msgMultipart = new MimeMultipart("mixed");
        MimeBodyPart mbpContent = new MimeBodyPart();

        // 判断处理邮件格式类型
        log.debug("处理邮件格式类型:" + type);
        if ("html".equals(type)) {
            mbpContent.setContent(content, "text/html;charset=utf-8");
        } else {
            mbpContent.setText(content);
        }
        msgMultipart.addBodyPart(mbpContent);

        // 处理邮件附件List
        if (attachmentList != null && attachmentList.size() > 0) {
            for (int i = 0; i < attachmentList.size(); ++i) {
                MimeBodyPart attachment = new MimeBodyPart();
                DataHandler dh = new DataHandler(new FileDataSource((String) attachmentList.get(i)));
                attachment.setDataHandler(dh);
                attachment.setFileName(MimeUtility.encodeWord(dh.getName()));
                msgMultipart.addBodyPart(attachment);
            }
        }

        message.setContent(msgMultipart);

        // 将文件内容写入本地服务器
        log.debug("SendMail将文件内容写入本地服务器Path:" + emlFilePath);
        File dirAll = new File(emlFilePath);

        // 文件夹路径是否存在不存在则创建
        File dir = new File(dirAll.getParent());
        if (!dir.exists()) {
            log.debug("SendMail创建EML路径:" + dirAll.getParent());
            dir.mkdirs();
        }

        FileOutputStream fos = null;
        try {
            // 检查目标文件是否存在，不存在则创建
            if (!dirAll.exists()) {
                log.debug("SendMail创建EML文件:" + dirAll.getName());
                dirAll.createNewFile();
            }
            // 向目标文件中写入内容
            fos = new FileOutputStream(dirAll);
            message.writeTo(fos);
            log.debug("SendMail写入EML文件完成...");

        } catch (IOException e) {
            log.error("SendMail写入EML文件失败：", e);
            e.printStackTrace();
        } finally {
            if (null != fos)
                try {
                    fos.close();
                } catch (IOException e) {
                    log.error("SendMail关闭文件流失败：", e);
                }
        }

        // 根据session对象获取邮件传输对象Transport
        log.debug("根据session对象获取邮件传输对象Transport");
        Transport transport = session.getTransport();

        // 设置发件人的账户名和密码
        log.debug("设置发件人的账户名和密码");
        transport.connect(username, password);

        // 发送邮件，并发送到所有收件人地址，message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
        log.debug("发送邮件并发送到所有收件人地址");
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        log.debug("发送邮件End...");
    }
}
